package com.td.lib.viewmodel;

import ohos.aafwk.ability.Ability;

/**
 * ViewModelProvider 负责提供ViewModel对象
 *
 * @since 2021/10/14
 */
public class ViewModelProvider {
    private static final String DEFAULT_KEY = "DefaultKey:";

    private final ViewModelStore mViewModelStore;

    public ViewModelProvider(ViewModelStore viewModelStore) {
        mViewModelStore = viewModelStore;
    }

    /**
     * 根据关键字获取ViewModel
     *
     * @param modelClass 类的class
     * @param <T> 类的泛型
     * @return ViewModel
     */
    public <T extends ViewModel> T get(Class<T> modelClass) {
        String canonicalName = modelClass.getCanonicalName();
        if (canonicalName == null) {
            throw new IllegalArgumentException("请使用非本地类和匿名类");
        }
        return get(DEFAULT_KEY + canonicalName, modelClass);
    }

    /**
     * 根据关键字获取ViewModel
     *
     * @param key 关键字
     * @param modelClass 类的class
     * @param <T> 类的泛型
     * @return ViewModel
     */
    public <T extends ViewModel> T get(String key, Class<T> modelClass) {
        ViewModel viewModel = mViewModelStore.get(key);
        if (viewModel == null) {
            viewModel = create(modelClass);
            mViewModelStore.put(key, viewModel);
        }
        return (T) viewModel;
    }

    private <T extends ViewModel> T create(Class<T> modelClass) {
        try {
            return modelClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("Cannot create an instance of " + modelClass, e);
        }
    }
}
